import { loadStripe } from '@stripe/stripe-js'
import API from '@/http'
import { themeFantasi } from './appearance'

/**
 * Stripe 設置意圖的 hook
 * 通常用於設置卡片
 * @property {Object} stripe
 * @property {Object} elements
 * @property {Object} paymentElement
 * @property {Function} confirm
 */
export async function useStripeSetup() {
  const { client_secret, publishable_key } = await API.Payment.getStripeKey()
  const stripe = await loadStripe(publishable_key)

  const elements = stripe.elements({
    clientSecret: client_secret,
    appearance: themeFantasi,
  })

  const paymentElement = elements.create('payment')

  async function confirm() {
    const { error } = await stripe.confirmSetup({
      elements,
      clientSecret: client_secret,
      confirmParams: { return_url: import.meta.env.VITE_APP_URL },
    })

    if (error) {
      console.error('Failed to confirm setup:', error)
      return false
    }
    return true
  }

  return { stripe, elements, paymentElement, confirm }
}
